package com.helloandroid.app.model

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.business.Analyse
import com.business.AnalyseKey
import com.business.TDKeys
import com.cy.game.PowerAddType
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.ext.*
import com.helloandroid.msg.Msg
import com.helloandroid.msg.MsgKey
import com.helloandroid.tools.*
import com.helloandroid.tools.GUtils.httpWithTimeOut
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.vo.*
import com.jf.game.JFResult
import com.jf.game.JFViewModel
import com.zp.game.ZhuanPanInfo
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.select
import org.json.JSONObject
import java.lang.Exception
import java.lang.StringBuilder
import kotlin.coroutines.resume

class UserViewModel : ViewModel() {

    // 登陆失败的时候,生成一个无效的 user
    private fun getInvalidUser(sysBs: Int): User = User(
            user_id = -1,
            coin = 0,
            money = 0,
            tx_count = 0,
            tx_time_stamp = 0L,
            bs = 0,
            bs_sys = sysBs,
            bs_target = 0,
            signed_count = 0,
            sign_time_stamp = 0L,
            wx_id = "",
            wx_name = "",
            wx_sex = 0,
            wx_icon = ""
    )

    fun login2(sysBs: Int, callback: (Boolean) -> Unit) {
        login(sysBs, true, callback)
    }

    fun bindWx(wxId: String, userId: Int, wxInfoStr: String, callback: (Boolean) -> Unit) {
        viewModelScope.launch {
            val jsonStr = asyncHttpReq("user/wxauth?user_id=${userId}&wx_id=${wxId}&wx_data=$wxInfoStr")
            val jsonObj = JSONObject(jsonStr)
            val parseResult = jsonObj.process(JSONObject::parseUser)
            if (parseResult.err == 0) {
                // 绑定成功
                val newUser = parseResult.obj as User
                newUser.loginTime = AppUtil.sysTime
                AppUtil.onLoginSuccess(newUser)
                zhuanReportTask(Type.BangdingWX)
                callback(true)
            } else {
                // 绑定失败
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false)
            }
        }
    }

    // 客户端发现到了新的一天的时候  才进行syncUser
    // 只有登陆成功,才修改当前的user并且清空 appCache
    // 同步失败,则不做别的处理, 稍后进行再次登陆
    fun syncUser(sysBs: Int, callback: (Boolean) -> Unit) {
        MyLog.elog("================ 新的一天 开始同步user数据=============================")
        if (!NetWorkUtil.networkConnected()) {
            callback(false)
            return
        }

        val userId = AppUtil.user.user_id
        val wxId = AppUtil.user.wx_id
        val url = loginUrl(userId, wxId, sysBs)
        viewModelScope.launch {

            // 解析json
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseUser)
            if (parseResult.err == 0) {
                val serverTime = jsonObj.getLong(GUtils.KeyTime)
                val newUser = parseResult.obj as User
                newUser.loginTime = serverTime
                AppUtil.onLoginSuccess(newUser)
                callback(true)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false)
            }
        }
    }

    private fun login(sysBs: Int, bToast: Boolean, callback: (Boolean) -> Unit) {
        MyLog.info("login2==>sysBs:$sysBs")
        if (!NetWorkUtil.networkConnected()) {
            if (bToast) {
                AppUtil.toast("请先连接到网络......")
            }
            AppUtil.onLoginFail(getInvalidUser(sysBs))
            callback(false)
            return
        }

        fun loginProcess(jsonStr: String) {
            if (jsonStr == "") {
                Analyse.report(AnalyseKey.Sys_LoginTimeout)
                AppUtil.onLoginFail(getInvalidUser(sysBs))
                callback(false)
            } else {
                // 解析json
                val jsonObj = JSONObject(jsonStr)
                val parseResult = jsonObj.process(JSONObject::parseUser)
                if (parseResult.err == 0) {
                    val serverTime = jsonObj.getLong(GUtils.KeyTime)
                    val newUser = parseResult.obj as User
                    newUser.loginTime = serverTime
                    AppUtil.onLoginSuccess(newUser)
                    callback(true)
                } else {
                    MyLog.info("err:${parseResult.err},msg:${parseResult.msg}")
                    AppUtil.onLoginFail(getInvalidUser(sysBs))
                    callback(false)
                }
            }
        }

        val userId = AppUtil.user.user_id
        val wxId = AppUtil.user.wx_id
        val url = loginUrl(userId, wxId, sysBs)
        viewModelScope.launch {
            httpWithTimeOut(8000, suspend {
                asyncHttpReq(url)
            }) { jsonStr ->
                loginProcess(jsonStr)
            }
        }
    }

    fun chgTarget(target: Int) {
        if (!NetWorkUtil.networkConnected()) {
            AppUtil.toast("请打开网络!")
            return
        }
        viewModelScope.launch {
            val url = "user/update/target?user_id=${AppUtil.user.user_id}&target=$target"
            val jsonObj = JSONObject(asyncHttpReq(url))
            var parseResult = jsonObj.process(JSONObject::parseChangeTarget)

            if (parseResult.err == 0) {
                AppUtil.toast("修改成功!")
                AppUtil.user.bs_target = target

                //  发一个广播出去.
//                val intent = Intent()
//                intent.action = AppConfig.Action_BsOrTarget_Changed
//                intent.putExtra(IntentKey.BsTarget, target)
//                intent.putExtra(IntentKey.CurBs, MyApplication.user.bs)
//                MyApplication.app.sendBroadcast(intent)

                // 目标改变了 也需要检查当日任务是否完成
                MyApplication.app.serverProxy?.sendMsgToServer(Msg.C2S_ChangeBsTarget,
                        Json {
                            MsgKey.BsTarget to target
                            MsgKey.CurBs to AppUtil.user.bs
                        }.toString())
                AppUtil.checkBsCompletion()
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    private fun loginUrl(user_id: Int, wx_id: String, sysBs: Int): String {
        var urlSb = StringBuilder("user/login?")
        if (user_id > 0) {
            urlSb.append("user_id=$user_id&")
            if (!wx_id.isNullOrEmpty()) {
                urlSb.append("wx_id=$wx_id&")
            }
            urlSb.append("sys_bushu=$sysBs")
        } else {
            urlSb.append("sys_bushu=$sysBs")
        }
        return urlSb.toString()
    }

    fun doubleAward(coinCount: Int) {
        viewModelScope.launch {
            val url = "user/awardcoin?user_id=${AppUtil.user.user_id}&coincount=${coinCount}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)

            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse

                // 增加金币  更新时间
                AppUtil.setCoin(coinResponse.total)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }


    //=====================================
    //
    fun zouAwardFreeCoin(type: Int, coinCount: Int) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "dashboard/freecoin?user_id=${AppUtil.user.user_id}&cointype=$type&coincount=$coinCount"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)

            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                val sysTime = AppUtil.sysTime
                when (type) {
                    ZouConstants.FreeCoin_1 -> {
                        AppCache.boardInfo?.cointime1 = sysTime
                    }
                    ZouConstants.FreeCoin_2 -> {
                        AppCache.boardInfo?.cointime2 = sysTime
                    }
                    ZouConstants.FreeCoin_3 -> {
                        AppCache.boardInfo?.cointime3 = sysTime
                    }
                    ZouConstants.FreeCoin_4 -> {
                        AppCache.boardInfo?.dailyCoinState = 1
                    }
                }
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    fun zouNewUserAward(coinCount: Int) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "dashboard/first_award?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)
            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                AppCache.boardInfo?.firstUsed = 1
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    fun zouAwardStepCoin(bsCount: Int) {
        val awardCoin = ZouConstants.StepMap[bsCount]
        AppUtil.increaseCoin(awardCoin!!)
        viewModelScope.launch {
            val url = "dashboard/step_award?user_id=${AppUtil.user.user_id}&award_id=$bsCount"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)

            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                AppCache.boardInfo?.bsCount = bsCount
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    //==================
    // zhuan
    fun zhuanGetAward(type: Type, coinCount: Int) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "task/award?user_id=${AppUtil.user.user_id}&task_id=${type.value}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)

            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                AppCache.taskInfo?.setStateToGeted(type)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    fun zhuanSign(awardCoin: Int) {
        AppUtil.increaseCoin(awardCoin)
        viewModelScope.launch {
            val url = "user/signup?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseSignResponse)
            if (parseResult.err == 0) {
                val signResponse = parseResult.obj as SignResponse
                AppUtil.setCoin(signResponse.total)
                AppUtil.updateSignInfo(signResponse.signTimeMs, signResponse.signedCount)

                //  通知服务端签到成功
                MyApplication.app.serverProxy?.sendMsgToServer(Msg.C2S_SignSuccess, "")

            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                AppUtil.toast("对不起,签到失败!")
            }
        }
    }

    // 早晚打卡
    fun zaoWanDaKa(coinCount: Int, time: TimeType) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "butie/zaowan/daka?user_id=${AppUtil.user.user_id}&timestate=${time.value}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)
            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                AppCache.zaoWanInfo?.let {
                    if (time == TimeType.ZAO) {
                        it.zaoExecuted = 1
                    } else {
                        it.wanExecuted = 1
                    }
                }

                // 上报早晚打卡
                zhuanReportTask(Type.ZaoWanDaKa)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 喝水打卡
    fun heShuiDaKa(itemId: Int, coinCount: Int) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "butie/heshui/daka?user_id=${AppUtil.user.user_id}&heshui_id=${itemId}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)
            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                AppCache.heShuiInfo?.setValueByHeShuiId(itemId, 1)

                // 上报喝水打卡
                zhuanReportTask(Type.HeShui)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 吃饭打卡
    fun chifanDaKa(cfId: Int, coinCount: Int) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "butie/chifan/daka?user_id=${AppUtil.user.user_id}&chifan_id=$cfId"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)

            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                AppCache.chiFanInfo?.setValueByChiFanId(cfId, 1, false)

                // 上报餐补
                zhuanReportTask(Type.ChiFan)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 每日运动领奖
    fun meiRiYunDongAward(item: SportDataItem) {
        AppUtil.increaseCoin(item.coinCount)
        viewModelScope.launch {
            val url = "butie/sport/award?user_id=${AppUtil.user.user_id}&yundong_id=${item.id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)
            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                AppCache.meiRiYunDongInfo?.let {
                    it.getSportItem(item.key).state = 1
                }
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 每日运动激活
    fun meiRiYunDongActive(item: SportDataItem) {
        viewModelScope.launch {
            val url = "butie/sport/active?user_id=${AppUtil.user.user_id}&yundong_id=${item.id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseEmpty)

            if (parseResult.err == 0) {
                AppCache.meiRiYunDongInfo?.let {
                    it.getSportItem(item.key).start = AppUtil.sysTime
                    MyLog.elog("激活了 ${item.key}... info:$it")
                }

                // 激活了就可以上报了
                zhuanReportTask(Type.TianTianYunDong)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 步数打卡
    fun buShuDaKa(awardCoin: Int) {
        AppUtil.increaseCoin(awardCoin)
        viewModelScope.launch {
            val url = "butie/bushu/daka?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)

            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)

                AppCache.bsInfo?.let {
                    it.state = 1
                }
                MyApplication.app.serverProxy?.sendMsgToServer(Msg.C2S_BuShuDaKaSuccess, "")
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 转盘上报抽奖结果
    fun zpReportResult(resultId: Int, count: Int) {
        viewModelScope.launch {
            val url = "game/zhuanpan/report?user_id=${AppUtil.user.user_id}&result_id=$resultId&count=$count"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseZhuanPanResponse)
            if (parseResult.err == 0) {
                val zpResponse = parseResult.obj as ZhuanPanResponse
                AppCache.zpInfo?.let {
                    it.resetCount = zpResponse.restcount
                    it.usedCount = zpResponse.usedcount
                    when (resultId) {
                        ZhuanPanInfo.Iphone12Pro -> it.iphone12Pro = zpResponse.count
                        ZhuanPanInfo.HwMate40Pro -> it.hwMate40 = zpResponse.count
                        ZhuanPanInfo.XiaoMi10Pro -> it.xiaomi10 = zpResponse.count
                        ZhuanPanInfo.OppoX -> it.oppoX = zpResponse.count
                        ZhuanPanInfo.VivoX60 -> it.vivoX60 = zpResponse.count

                        ZhuanPanInfo.BigCoin,
                        ZhuanPanInfo.MidCoin,
                        ZhuanPanInfo.SmallCoin -> {
                            AppUtil.setCoin(zpResponse.count)
                        }
                    }
                }

                // 上报转盘任务
                zhuanReportTask(Type.ZhuanPan)

            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 转盘额外奖励   5次/15次/30次
    fun zpExtraAward(awardId: Int, coinCount: Int) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "game/zhuanpan/extra?user_id=${AppUtil.user.user_id}&award_id=${awardId + 1}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseZpExtraAward)
            if (parseResult.err == 0) {
                val zpExtraAward = parseResult.obj as ZpExtraAward
                AppUtil.setCoin(zpExtraAward.total)
                AppCache.zpInfo?.let {
                    it.updateAwardState(awardId, 1)
                }
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 红包雨上报游戏时间
    fun hbyReportTimeMs() {
        viewModelScope.launch {
            val url = "game/hongbaoyu/start?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseEmpty)
            if (parseResult.err == 0) {

                AppCache.hbyInfo?.let {
                    MyLog.elog("============== 更新红包上报时间成功============")
                    it.lastTimeMs = AppUtil.sysTime
                }
                // 保存上次玩的时间,用于通知判断
                MyApplication.app.serverProxy?.sendMsgToServer(Msg.C2S_PlayHby, "")
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    // 红包雨奖励
    fun hbyAward(coinCount: Int) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "game/hongbaoyu/award?user_id=${AppUtil.user.user_id}&coincount=$coinCount"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseHbyAwardResponse)
            if (parseResult.err == 0) {
                val hbyAwardResponse = parseResult.obj as HbyAwardResponse
                AppUtil.setCoin(hbyAwardResponse.total)
                AppCache.hbyInfo?.let {
                    it.count = hbyAwardResponse.count
                }

                // 上报红包雨
                zhuanReportTask(Type.HongBaoYu)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    fun cyPassLevel(level: Int, coinCount: Int) {
        AppUtil.increaseCoin(coinCount)
        viewModelScope.launch {
            val url = "game/chengyu/award?user_id=${AppUtil.user.user_id}&curlevel=$level"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)

            if (parseResult.err == 0) {
                val coinResponse = parseResult.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
                AppCache.cyInfo?.let {
                    it.curLevel++
                }
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    fun cyExtraAward(passedLevel: Int, awardCoin: Int) {
        AppUtil.increaseCoin(awardCoin)
        viewModelScope.launch {
            val url = "/game/chengyu/extra?user_id=${AppUtil.user.user_id}&curlevel=$passedLevel"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResponse = jsonObj.process(JSONObject::parseCoinResponse)
            if (parseResponse.err == 0) {
                val coinResponse = parseResponse.obj as CoinResponse
                AppUtil.setCoin(coinResponse.total)
            } else {
                MyLog.elog("err:${parseResponse.err},msg:${parseResponse.msg}")
            }
        }
    }

    fun cyHint() {
        viewModelScope.launch {
            val url = "game/chengyu/hint?user_id=${AppUtil.user.user_id}"
            val jsonStr = asyncHttpReq(url)

            val jsonObj = JSONObject(jsonStr)
            val parseResult = jsonObj.process(JSONObject::parseCyHintResponse)
            if (parseResult.err == 0) {
                val restTipCount = parseResult.obj as Int
                AppCache.cyInfo?.let {
                    it.tipCount = restTipCount
                }
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    fun cyRepower(time: Long, count: Int, isVideo: Boolean) {
        // 1. 正常倒计时
        // 2. 看视频
        val powerAddType = if (isVideo) PowerAddType.Video else PowerAddType.Normal
        viewModelScope.launch {
            val url = "game/chengyu/poweradd?user_id=${AppUtil.user.user_id}&addPower=$count&isVideo=${powerAddType.value}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parsePower)
            if (parseResult.err == 0) {
                val power = parseResult.obj as Int
                AppCache.cyInfo?.let {
                    it.power = power
                    it.lastRepowerMs = time
                }
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    fun cyConsumePower(full: Boolean = true) {
        viewModelScope.launch {
            val url = "game/chengyu/start?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parsePower)

            if (parseResult.err == 0) {

                val power = parseResult.obj as Int
                AppCache.cyInfo?.let {
                    it.power = power
                    if (full) {
                        it.lastRepowerMs = AppUtil.sysTime   //加入是满能量消耗的话，以消耗时间来计算下次补给时间
                    }
                }
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }


    //============================================
    // 上报赚赚里面的任务
    //        1. 首次提现上报   (已上报)
    //       2. 目标步数的上报   (已上报)
    //       3. 绑定微信的上报    (已上报)
    //       4. 每日分享的上报     TODO
    //       5. 天天运动  (已上报)
    //       6. 看视频    (已上报)
    //       7. 喝水打卡  (已上报)
    //       8. 转盘  (已上报)
    //       9. 成语   (已上报)
    //       10. 红包雨  (已上报)
    //       11. 早晚打卡  (已上报)
    //       12. 餐补打卡  (已上报)
    //       13. 天天红包赛 (已上报)
    //       14. 集福  (已上报)
    fun zhuanReportTask(type: Type) {
        viewModelScope.launch {
            val jsonStr = asyncHttpReq("task/report?user_id=${AppUtil.user.user_id}&task_id=${type.value}")
            val jsonObj = JSONObject(jsonStr)
            val parseResult = jsonObj.process(JSONObject::parseTaskReportResponse)
            if (parseResult.err == 0) {
                AppCache.taskInfo?.let {
                    val reportRes = parseResult.obj as TaskReportResponse
                    // 同步本地状态
                    when (type) {
                        Type.Shoucitixian -> it.firstTx.setByRes(reportRes)
                        Type.BuShu -> it.bushu.setByRes(reportRes)
                        Type.BangdingWX -> it.bindwx.setByRes(reportRes)
                        Type.Share -> it.share.setByRes(reportRes)
                        Type.TianTianHongBao -> it.hbMatch.setByRes(reportRes)
                        Type.TianTianYunDong -> it.sport.setByRes(reportRes)
                        Type.ViewVideo -> it.video.setByRes(reportRes)
                        Type.HeShui -> it.heShui.setByRes(reportRes)
                        Type.ZhuanPan -> it.zhuanPan.setByRes(reportRes)
                        Type.ChengYu -> it.chengYu.setByRes(reportRes)
                        Type.HongBaoYu -> it.hongBaoYu.setByRes(reportRes)
                        Type.JiFuZi -> it.jifuzi.setByRes(reportRes)
                        Type.ZaoWanDaKa -> it.zaoWan.setByRes(reportRes)
                        Type.ChiFan -> it.chiFan.setByRes(reportRes)
                        Type.JiFuZi -> it.jifuzi.setByRes(reportRes)
                    }
                }
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
            }
        }
    }

    fun tx(fenAmount: Int, callback: (Boolean) -> Unit) {
        if (!NetWorkUtil.networkConnected()) {
            AppUtil.toast("请打卡网络!")
            callback(false)
            return
        }

        viewModelScope.launch {
            val jsonStr = asyncHttpReq("tx/req?user_id=${AppUtil.user.user_id}&wx_id=${AppUtil.user.wx_id}&money=${fenAmount}")
            val jsonObj = JSONObject(jsonStr)

            val parseResult = jsonObj.process(JSONObject::parseEmpty)
            if (parseResult.err == 0) {

                AppUtil.toast("恭喜,提现成功!")

                zhuanReportTask(Type.Shoucitixian)

                // 认为提现成功. 减少money
                //  发送通知
                AppUtil.user.money -= fenAmount * 100
//                val intent = Intent(AppConfig.Action_CoinOrMoney_Changed)
//                MyApplication.app.sendBroadcast(intent)

                // 添加一条记录
                val txItem = TxItem(fenAmount, AppUtil.sysTime)
                AppCache.txInfo?.arr?.add(txItem)
                callback(true)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                // 提现失败
                AppUtil.toast("${parseResult.msg}")
                callback(false)
            }
        }
    }

    fun fakeTx(fenAmount: Int, callback: (Boolean) -> Unit) {
        if (!NetWorkUtil.networkConnected()) {
            AppUtil.toast("请打卡网络!")
            callback(false)
            return
        }
        viewModelScope.launch {
            // val jsonStr = asyncHttpReq("tx/req?user_id=${MyApplication.user.user_id}&wx_id=${MyApplication.wx_id}&money=${fenAmount}")

            val defer = async(Dispatchers.IO) {
                """{"err":0,"msg":"fake提现成功!"}
                """.trimIndent()
            }

            val jsonObj = JSONObject(defer.await())

            val parseResult = jsonObj.process(JSONObject::parseEmpty)
            if (parseResult.err == 0) {

                AppUtil.toast("恭喜,提现成功!")

                zhuanReportTask(Type.Shoucitixian)

                // 认为提现成功. 减少money
                //  发送通知
                AppUtil.user.money -= fenAmount * 100
//                val intent = Intent(AppConfig.Action_CoinOrMoney_Changed)
//                MyApplication.app.sendBroadcast(intent)

                // 添加一条记录
                val txItem = TxItem(fenAmount, AppUtil.sysTime)
                AppCache.txInfo?.arr?.add(txItem)
                callback(true)
            } else {
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                // 提现失败
                AppUtil.toast("${parseResult.msg}")
                callback(false)
            }
        }
    }

    //  timeOut <= 0 表示不需要超时
    //  timeOut > 0 表示需要应用超时
    fun loadServerConfig(timeOut: Long = -1L, callback: (String?) -> Unit) {
        if (timeOut > 0) {
            viewModelScope.launch {
                httpWithTimeOut(timeOut, suspend { asyncHttpReq(TDKeys.ServerCfgUrl, false) }){jsonStr->
                    callback(jsonStr)
                }
            }
        } else {
            viewModelScope.launch {
                val serverStr = asyncHttpReq(TDKeys.ServerCfgUrl, false)
                MyLog.info("读取服务端配置成功....")
                withContext(Dispatchers.Main) {
                    callback(serverStr)
                }
            }
        }
    }

    // 集福
    fun jfRoll(jfResult: JFResult) {
        viewModelScope.launch {
            val jsonStr = asyncHttpReq("game/niudan/award?user_id=${AppUtil.user.user_id}&result_id=${jfResult.result_id}&count=${jfResult.count}")
            val jsonObj = JSONObject(jsonStr)
            val parseResult = jsonObj.process(JSONObject::parseJFAwardResponse)
            if (parseResult.err == 0) {
                zhuanReportTask(Type.JiFuZi)
                val awardResponse = parseResult.obj as JFAwardResponse
                AppCache.jfInfo?.let {
                    when (awardResponse.resultId) {
                        JFViewModel.Fu -> it.fu = awardResponse.count
                        JFViewModel.Lu -> it.lu = awardResponse.count
                        JFViewModel.Shou -> it.shou = awardResponse.count
                        JFViewModel.Xi -> it.xi = awardResponse.count
                        JFViewModel.Cai -> it.cai = awardResponse.count
                        JFViewModel.Coin -> AppUtil.setCoin(awardResponse.count)
                    }
                    it.restcount = awardResponse.restCount
                }
            }
        }
    }
}